import { Interruptible, InterruptStatus } from '../types';

/**
 * 中断控制器 - 管理全局中断逻辑
 * 支持ESC键中断AI流式响应、MCP工具调用等操作
 */
class InterruptController {
  private interruptibles: Set<Interruptible> = new Set();
  private status: InterruptStatus = { isInterrupting: false };
  private listeners: Array<(status: InterruptStatus) => void> = [];

  /**
   * 注册可中断的服务
   */
  addInterruptible(service: Interruptible): void {
    this.interruptibles.add(service);
  }

  /**
   * 移除可中断的服务
   */
  removeInterruptible(service: Interruptible): void {
    this.interruptibles.delete(service);
  }

  /**
   * 执行全局中断
   */
  async interrupt(reason = 'User interrupted'): Promise<void> {
    if (this.status.isInterrupting) {
      return; // 已在中断中，避免重复
    }

    this.status = {
      isInterrupting: true,
      reason,
      timestamp: new Date()
    };

    this.notifyListeners();

    try {
      // 并行中断所有服务
      const interruptPromises = Array.from(this.interruptibles).map(service => 
        service.interrupt(reason).catch(error => {
          console.error('服务中断失败:', error);
        })
      );

      await Promise.allSettled(interruptPromises);
    } finally {
      this.status = { isInterrupting: false };
      this.notifyListeners();
    }
  }

  /**
   * 检查是否正在中断
   */
  isInterrupting(): boolean {
    return this.status.isInterrupting;
  }

  /**
   * 获取当前中断状态
   */
  getStatus(): InterruptStatus {
    return { ...this.status };
  }

  /**
   * 监听中断状态变化
   */
  onStatusChange(listener: (status: InterruptStatus) => void): () => void {
    this.listeners.push(listener);
    
    // 返回取消监听函数
    return () => {
      const index = this.listeners.indexOf(listener);
      if (index > -1) {
        this.listeners.splice(index, 1);
      }
    };
  }

  /**
   * 通知所有监听器状态变化
   */
  private notifyListeners(): void {
    this.listeners.forEach(listener => {
      try {
        listener(this.getStatus());
      } catch (error) {
        console.error('中断状态监听器错误:', error);
      }
    });
  }

  /**
   * 清理所有服务和监听器
   */
  cleanup(): void {
    this.interruptibles.clear();
    this.listeners.length = 0;
    this.status = { isInterrupting: false };
  }
}

// 导出单例
export const interruptController = new InterruptController();